/*
 * @Description: 时间差
 * @Author: chenjiaxin
 * @Date: 2022-02-02 17:58:57
 * @LastEditTime: 2022-03-10 20:51:17
 * @FilePath: \super-unit\lib\time\differ.js
 */
let minute_s = 60; // 1 minute 60s
let hour_s = 60 * minute_s; // 1 hour 60*60s
let day_s = 24 * hour_s; // 1 day 24 * hour

/**
 * 获取当前时间距离某日期时间 还要几天 几小时 几分钟 几秒
 * @param {String} target 日期时间 字符串
 * @returns Object
 */
const spaceTime = (target) => {
  let day = 0;
  let hour = 0;
  let minute = 0;
  let second = 0;

  let space = spaceTimeSecond(target); // 差值 秒
  if (space <= 0) {
    // throw "日期错误";
    return {
      day,
      hour,
      minute,
      second
    };
  }
  if (space > day_s) {
    day = parseInt(space / day_s);
    space = space % day_s;
  }
  if (space > hour_s) {
    hour = parseInt(space / hour_s);
    space = space % hour_s;
  }
  if (space > minute_s) {
    minute = parseInt(space / minute_s);
    space = space % minute_s;
  }
  second = space;

  return {
    day,
    hour,
    minute,
    second
  };
};

/**
 * 获取与当前时间的时间差
 * @param {String | Number} target 日期时间 字符串 | 时间戳
 * @returns 传入的日期时间 与 现在的 时间差(时间戳)000000
 */
const spaceTimeSecond = (target) => {
  let target_code = 0;
  //判断是否时间戳
  if (typeof target === "number") {
    //日期时间 时间戳
    target_code = target;
  } else if (typeof target === "string") {
    // throw "type error";
    //日期时间 字符串
    target = target.replaceAll("-", "/"); //兼容ios系统
    let typeArr = target.split(" ");
    let ymd = typeArr[0];
    let hms = typeArr[1];
    if (hms && hms.split(":").length !== 3) {
      throw "type error";
    }

    if (!hms) hms = "00:00:00";

    target_code = new Date(`${ymd} ${hms}`).getTime();
    target_code = parseInt(target_code / 1000); // 转 秒
  }

  let now_code = new Date().getTime();
  now_code = parseInt(now_code / 1000);
  return target_code - now_code;
};

module.exports = {
  spaceTime
};
